//
//  ZYVisitorAnimationView.swift
//  SwiftDemo1
//
//  Created by wzp on 2025/6/2.
//

import Foundation
import UIKit

class ZYVisitorAnimationView: UIView {
    private var animationView: UIImageView = UIImageView()
    private var bgImageView: UIImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        layoutUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - UI
extension ZYVisitorAnimationView {
    
    private func setupUI() {
        animationView.contentMode = .scaleAspectFill
        animationView.layer.anchorPoint = CGPointMake(0.5, 0.5)
        
        bgImageView.contentMode = .scaleAspectFit
        
        addSubview(animationView)
        addSubview(bgImageView)
    }
    
    private func layoutUI() {
        bgImageView.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.height.equalTo(100)
            make.center.equalTo(self.snp.center)
        }
        
        animationView.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(180, 180))
            make.center.equalTo(self.snp.center)
        }
    }
    
    func updateUI(_ bgImageName: String, animationImageName: String) {
        bgImageView.image = UIImage(named: bgImageName)
        animationView.image = UIImage(named: animationImageName)
    }
    
    func startAnimation() {
        let keyAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
        keyAnimation.repeatCount = Float.infinity
        keyAnimation.values = [0, Double.pi, Double.pi * 2]
        keyAnimation.keyTimes = [0, 0.5, 1]
        keyAnimation.duration = 8
        keyAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
        keyAnimation.isRemovedOnCompletion = false
        
        animationView.layer.add(keyAnimation, forKey: "animationView")
    }
    
    func stopAnimation() {
        animationView.layer.removeAllAnimations()
    }
    
}
